/*
 * Copyright 2012 Claude Houle claude.houle@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.mochaccino.framework.dbtool.impl;

import ch.qos.logback.core.joran.spi.JoranException;
import com.google.code.mochaccino.framework.dbtool.CommandLine;
import com.google.code.mochaccino.framework.dbtool.liquibase.LiquibaseProvider;
import com.google.code.mochaccino.framework.dbtool.liquibase.LiquibaseProviderDS;
import com.google.code.mochaccino.framework.dbtool.liquibase.LiquibaseProviderHibernate;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import liquibase.database.Database;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class Diff extends CommandLine {

	private Option OPT_CREATE_SCHEMA = null;
	private Option OPT_DROP_SCHEMA   = null;
	private Option OPT_DIR           = null;

	private   boolean createSchema = false;
	private   boolean dropSchema   = false;
	protected File    dir          = null;

	/** Constructor */
	public Diff() throws JoranException {
		super();
	}

	@Override
	protected Options createOptions() {
		Options options = new Options();
		options.addOption( OPT_MODULE );

		OPT_CREATE_SCHEMA = new Option( "create", false, "" );
		OPT_CREATE_SCHEMA.setRequired( false );
		options.addOption( OPT_CREATE_SCHEMA );

		OPT_DROP_SCHEMA = new Option( "drop", false, "" );
		OPT_DROP_SCHEMA.setRequired( false );
		options.addOption( OPT_DROP_SCHEMA );

		OPT_DIR = new Option( "output", true, "" );
		OPT_DIR.setArgName( "DIR" );
		OPT_DIR.setArgs( 1 );
		OPT_DIR.setRequired( false );
		options.addOption( OPT_DIR );

		return options;
	}

	@Override
	protected void execute() {
		LiquibaseProvider targetProvider = new LiquibaseProviderDS( target );
		LiquibaseProviderHibernate referenceProvider = new LiquibaseProviderHibernate( reference, configuration );

		try {
			targetProvider.initialize();
			referenceProvider.initialize();

			SimpleDateFormat format = new SimpleDateFormat( "yyyyMMddHHmmss" );
			File filename = new File( dir, FILE_NAME_PREFIX + "-" + format.format( new Date() ) + FILE_NAME_SUFFIX );
			if ( createSchema ) {
				referenceProvider.createSchema();
			}

			Database targetDB = targetProvider.getDatabase();
			Database referenceDb = referenceProvider.getDatabase();
			liquibase.diff.Diff d = new liquibase.diff.Diff( referenceDb, targetDB );
			d.setDiffColumns( true );
			d.setDiffData( true );
			d.setDiffForeignKeys( true );
			d.setDiffIndexes( true );
			d.setDiffPrimaryKeys( true );
			d.setDiffSequences( true );
			d.setDiffTables( true );
			d.setDiffUniqueConstraints( true );
			d.setDiffViews( true );

			liquibase.diff.DiffResult result = d.compare();
			result.printChangeLog( filename.getAbsolutePath(), targetDB );

			if ( dropSchema ) {
				referenceProvider.dropSchema();
			}
		} catch ( Exception e ) {
			exit( 2, e );
		} finally {
			try {
				referenceProvider.destroy();
				targetProvider.destroy();
			} catch ( Exception e ) {
				exit( 2, e );
			}
		}
	}

	@Override
	protected void interpretArgsBeforeInjection( String[] args ) {
		super.interpretArgsBeforeInjection( args );

		try {
			org.apache.commons.cli.CommandLine parsedArgs = parseArgs( args );
			createSchema = parsedArgs.hasOption( OPT_CREATE_SCHEMA.getOpt() );
			dropSchema = parsedArgs.hasOption( OPT_DROP_SCHEMA.getOpt() );

			dir = new File( parsedArgs.hasOption( OPT_DIR.getOpt() ) ? parsedArgs.getOptionValue( OPT_DIR.getOpt() ) : DIR );
			if ( !dir.exists() ) {
				if ( !dir.mkdirs() ) {
					exit( 1, "File '" + dir.getAbsolutePath() + "' could not be created" );
				}
			}

			if ( !dir.isDirectory() ) {
				exit( 1, "File '" + dir.getAbsolutePath() + "' is not a directory" );
			}
		} catch ( ParseException e ) {
			exit( 2, e );
		}
	}

	public static final void main( String[] args ) throws JoranException {
		Diff tool = new Diff();
		tool.start( args );
	}
}
